package com.example.lock;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import org.jetbrains.annotations.NotNull;

import java.util.List;


public class MainActivity extends AppCompatActivity {

    private boolean isServiceRun;
    // 动态申请权限
    private static final int REQUEST_PERMISSION_CODE = 0;
    private String[] permissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,// 写入数据权限
            Manifest.permission.READ_EXTERNAL_STORAGE,// 读取数据权限
            Manifest.permission.SYSTEM_ALERT_WINDOW
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        isServiceRun = isServiceRunning(this, ".MainService");
        moveTaskToBack(true);
        if (isServiceRun) {
            return;
        }
        isCanDrawOverlays();
    }

    public boolean isCanDrawOverlays() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                Toast.makeText(this, "当前无浮窗权限，请授权", Toast.LENGTH_SHORT);
                startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 0);
                return false;
            } else {
                checkPermission(MainActivity.this);
                return true;
            }

        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        isCanDrawOverlays();
    }

    public static boolean isServiceRunning (Context mContext, String className){

            boolean isRunning = false;
            ActivityManager activityManager = (ActivityManager) mContext
                    .getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                    .getRunningServices(30);

            if (!(serviceList.size() > 0)) {
                return false;
            }

            for (int i = 0; i < serviceList.size(); i++) {
                if (serviceList.get(i).service.getClassName().contains(className) == true) {
                    isRunning = true;
                    break;
                }
            }
            return isRunning;
        }


        /**
         * @param activity
         */
        public void checkPermission (AppCompatActivity activity){
            if (Build.VERSION.SDK_INT >= 23) {
                int checkPermission =
                                 ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                + ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
                if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    ActivityCompat.requestPermissions(activity, new String[]{
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    //有权限
                    LockService.saveActivity(MainActivity.this);
                    Intent mIntent = new Intent(MainActivity.this, LockService.class);
                    isServiceRun = true;
                    startService(mIntent);
                    finish();
                }
            }
            return;
        }


        @Override
        public void onRequestPermissionsResult ( int requestCode,
        @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults){
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode == 1) {

                boolean isAllAllow = true;
                for (int i = 0; i < permissions.length; i++) {
                    //已授权
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        Log.i("SQS","onRequestPermissionsResult");
                        isAllAllow = false;
                    }
                }

                if (isAllAllow) {
                    LockService.saveActivity(MainActivity.this);
                    Intent mIntent = new Intent(MainActivity.this, LockService.class);
                    isServiceRun = true;
                    startService(mIntent);
                } else {
                    Toast.makeText(MainActivity.this, "缺少必要权限", Toast.LENGTH_SHORT).show();
                }
                finish();
            }


        }

    }